package com.hust360.percent.pojo;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.Image.ImageDAO;

public class ImageDAOImpl implements ImageDAO {

	SQLiteDatabase db;

	public ImageDAOImpl(PercentApplication application) {
		db = application.getLocalDB();
	}

	@Override
	public List<Image> findByDscId(Long dscid) {
		Cursor c;
		List<Image> list;
		Image img;

		synchronized (db) {
			c = db.rawQuery("SELECT * FROM image WHERE dscid=?",
					new String[] { dscid + "" });
		}

		list = new ArrayList<Image>(c.getCount());
		while (c.moveToNext()) {
			img = new Image();
			img.dscid = c.getLong(c.getColumnIndex(Image.DSCID));
			img.filename = c.getString(c.getColumnIndex(Image.FILENAME));
			img.id = c.getLong(c.getColumnIndex(Image.ID));
			img.url = c.getString(c.getColumnIndex(Image.URL));
			list.add(img);
		}
		c.close();
		return list;
	}

	@Override
	public void save(Image image) {
		ContentValues values = new ContentValues();
		values.put(Image.DSCID, image.dscid);
		values.put(Image.FILENAME, image.filename);
		values.put(Image.URL, image.url);
		synchronized (PercentApplication.localDB) {
			PercentApplication.localDB.insertWithOnConflict(Image.TABLE, null,
					values, SQLiteDatabase.CONFLICT_REPLACE);
		}
	}

}
